package com.mszlu.blog.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.mszlu.blog.dao.mapper.ArticleMapper;
import com.mszlu.blog.dao.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * User: SJP
 * Date: 2022/3/2
 * Time: 13:37
 *
 * @author sjp
 * Description: No Description
 */
@Component
public class ThreadService {
    //期望此操作在线程池中执行，不影响原有的主线程
    //这里的线程池看不懂，可以去看juc并发编程
    @Async("taskExecutor")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {

        int viewCount = article.getViewCounts();
        //在mybatisplus中，只要在对象Article中有属性不为NULL，那么其就会生成到sql语句中
        //解决方法就是把属性都设置为包装类，无默认值，基本类型有默认值，除char外
        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(viewCount + 1);
        LambdaUpdateWrapper<Article> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Article::getId,article.getId());
        //设置一个 为了在多线程的环境下 线程安全
        lambdaUpdateWrapper.eq(Article::getViewCounts,viewCount);
        articleMapper.update(articleUpdate,lambdaUpdateWrapper);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新完成");
    }
}
